import { getFormData, getFormSaveData, saveFormData, saveFormSaveData } from "@/views/formgen/utils/db";
import { ref } from "vue";
import { getFormRecoveryData, saveFormRecoveryData } from "@/api/project/form";
import { useThrottleFn } from "@vueuse/core";
import { useUserFormInject } from "@/views/formgen/components/GenerateForm/hooks/useUserFormInject";
import { cloneDeep } from "lodash-es";

/**
 * 表单数据恢复
 */
export function useFormDataRecovery() {
  // 未提交的数据
  const notSubmitFormData = ref<Record<string, any>>({});
  // 上次提交的数据
  const lastSubmitFormData = ref<Record<string, any>>({});

  // 显示哪些恢复按钮
  const showRestoreDataBtnList = ref<number[]>([]);

  const showConfirm = ref(false);

  const formStore = useUserFormInject();
  const { extractInfo, currentPageConfig } = formStore;

  // 判断对象是否不为空
  const isEmpty = (obj: any) => {
    return !obj || Object.keys(obj).length === 0;
  };

  // 判断对象是否是空的或者每个字段的值都是undefined
  const isEmptyObject = (obj: any) => {
    return !obj || Object.keys(obj).every(key => obj[key] === undefined);
  };

  /**
   * 检测是否存在可恢复的数据
   */
  const checkRestoreData = async () => {
    // 查询未提交的数据用来恢复
    if (currentPageConfig?.value?.setting && currentPageConfig?.value?.setting?.saveNotSubmitStatus) {
      notSubmitFormData.value = await getRestoreData(1);
      console.log(notSubmitFormData.value);
      if (!isEmpty(notSubmitFormData.value)) {
        showConfirm.value = true;
        showRestoreDataBtnList.value.push(1);
      }
    }
    // 已提交数据
    if (currentPageConfig?.value?.setting && currentPageConfig?.value?.setting?.saveSubmitStatus) {
      lastSubmitFormData.value = await getRestoreData(2);
      if (!isEmpty(lastSubmitFormData.value)) {
        showConfirm.value = true;
        showRestoreDataBtnList.value.push(2);
      }
    }
  };

  /**
   * 恢复数据
   */
  const restoreData = async (parseKey: any, restoreType: number) => {
    let tempFormModel: Record<string, any> = {};
    if (restoreType == 1) {
      tempFormModel = cloneDeep(notSubmitFormData.value);
    } else {
      tempFormModel = cloneDeep(lastSubmitFormData.value);
    }

    if (restoreType) {
      formStore.setFormModel(tempFormModel);
      formStore.setIsRecoverFormData(true);
      showRestoreDataBtnList.value = [];
      showConfirm.value = false;
    }
  };

  // 判断两个对象是否相等
  const isEqual = (a: any, b: any) => {
    return JSON.stringify(a) === JSON.stringify(b);
  };

  const saveRecoveryData = (type: number, id: string, formModel: any, dataType: number) => {
    if (!id) {
      return;
    }
    console.log("formModel");
    if (isEmpty(formModel)) {
      return;
    }
    // 如果是暂存 对比下跟上次提交的数据是否相等 避免恢复了上次提交的数据后 触发了暂存  把草稿数据覆盖了
    if (dataType == 1 && isEqual(formModel, lastSubmitFormData.value)) {
      return;
    }

    saveFormRecoveryData({
      dataType: dataType,
      formKey: currentPageConfig?.value?.formKey as string,
      dataContent: formModel,
      associationId: id,
      associationType: type
    });
  };

  const throttledSaveRecoveryData = useThrottleFn(
    (type: number, id: string, formModel: any, dataType: number) => {
      saveRecoveryData(type, id, formModel, dataType);
    },
    2000,
    true
  );

  /**
   * 保存数据
   * @param formModel
   * @param dataType 数据类型  1. 未提交数据  2. 已提交数据
   * 保存位置
   * 1. 本地缓存
   * 2. 账号保存c
   * 3. 云端保存
   */
  const saveFormRestoreData = (formModel: any, dataType: number): void => {
    let saveType = "1";
    if (dataType == 1) {
      saveType = currentPageConfig?.value?.setting?.saveNotSubmitDataType || "1";
    } else if (dataType == 2) {
      saveType = currentPageConfig?.value?.setting?.saveSubmitDataType || "1";
    }
    if (isEmptyObject(formModel)) {
      return;
    }
    const saveLocalCache = () => {
      if (dataType == 1) {
        saveFormData(formModel, currentPageConfig?.value?.formKey);
      } else if (dataType == 2) {
        saveFormSaveData(formModel, currentPageConfig?.value?.formKey as string);
      }
    };
    switch (saveType) {
      case "1":
        saveLocalCache();
        break;
      case "2":
      case "3":
        // 后端自动获取账号 传个-1就好
        const id = saveType == "2" ? "-1" : (extractInfo.whilteListVal as string);
        if (dataType == 1) {
          throttledSaveRecoveryData(Number(saveType), id, formModel, dataType);
        } else {
          saveRecoveryData(Number(saveType), id, formModel, dataType);
        }
        break;
      default:
        saveLocalCache();
    }
  };

  const getRecoveryData = async (type: number, id: string, dataType: number) => {
    if (!id) {
      return;
    }
    const res = await getFormRecoveryData({
      formKey: currentPageConfig?.value?.formKey as string,
      associationId: id,
      associationType: type,
      dataType: dataType
    });
    if (res.data && res.data.dataContent) {
      return res.data.dataContent;
    }
    return null;
  };

  /**
   * 获取需要恢复的数据
   * @param dataType 数据类型 已提交 还是未提交的
   */
  const getRestoreData = async (dataType: number) => {
    let formModel: any = {};
    let saveType = "1";
    if (dataType == 1) {
      saveType = currentPageConfig?.value?.setting?.saveNotSubmitDataType || "1";
    } else if (dataType == 2) {
      saveType = currentPageConfig?.value?.setting?.saveSubmitDataType || "1";
    }
    const getLocalCache = () => {
      if (dataType == 1) {
        formModel = getFormData(currentPageConfig?.value?.formKey as string);
      } else if (dataType == 2) {
        formModel = getFormSaveData(currentPageConfig?.value?.formKey as string);
      }
      return formModel;
    };
    switch (saveType) {
      case "1":
        formModel = getLocalCache();
        break;
      case "2":
        formModel = await getRecoveryData(2, "-1", dataType);
        break;
      case "3":
        formModel = await getRecoveryData(3, extractInfo.whilteListVal || "", dataType);
        break;
      default:
        formModel = getLocalCache();
    }
    return formModel;
  };

  return {
    showRestoreDataBtnList,
    restoreData,
    saveFormRestoreData,
    checkRestoreData,
    showConfirm
  };
}
